﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using DataAccess;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Serialization;

namespace KhoaLuan.Account
{
    public partial class ResetPassword : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["UserResetPass"] = null;
                var ResetCode = Request.QueryString["ResetCode"];
                if (ResetCode != null)
                {
                    tbUsers_Proxy proxy = new tbUsers_Proxy();
                    var tbuser = proxy.GetByResetCode_tbUsers_Proxy(ResetCode);
                    if (tbuser != null && tbuser.DeadlineReset != null)
                    {
                        Session["UserResetPass"] = tbuser;
                    }
                }
            }
        }

        [WebMethod]
        public static string ResetPass(string newpass)
        {
            try
            {
                var tbuser = HttpContext.Current.Session["UserResetPass"] as tbUsers;
                tbUsers_Proxy proxy = new tbUsers_Proxy();
                if (tbuser != null)
                {
                    if ((tbuser.DeadlineReset.Value - DateTime.Now).TotalMinutes < 0)
                    {
                        return new JavaScriptSerializer().Serialize(new { Status = "Error", Cause = "Hết thời gian xử lý" });
                    }
                    else
                    {
                        tbuser.Password = EncryptData.Encryption(newpass);
                        if (proxy.Update_tbUsers_Proxy(tbuser))
                        {
                            HttpContext.Current.Session["UserResetPass"] = null;
                            return new JavaScriptSerializer().Serialize(new { Status = "Success" });
                        }
                    }
                }
                return new JavaScriptSerializer().Serialize(new { Status = "Error", Cause = "Hết thời gian xử lý" });
            }
            catch (Exception)
            {
                return new JavaScriptSerializer().Serialize(new { Status = "Error", Cause = "Không thể thay đổi mật khẩu" });
            }
        }
    }
}